<?php

namespace App\Api;

use PhalApi\Api;
use function App\Checkimei;


/**
 * 万国觉醒 取token-
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */
class RokGetToken extends Api
{
    public function getRules()
    {
        return array(
            'Rest'    => array(
                'imei'       => array('name' => 'imei', 'desc' => 'imei'),
                'phone_name' => array('name' => 'phone_name', 'desc' => 'phone_name'),
                'note'       => array('name' => 'note', 'desc' => 'note'),
            ),
            'newRest' => array(
                'imei'       => array('name' => 'imei', 'desc' => 'imei'),
                'phone_name' => array('name' => 'phone_name', 'desc' => 'phone_name'),
                'note'       => array('name' => 'note', 'desc' => 'note'),
            ),
            'Qu'      => array(
                'qus' => array('name' => 'qus', 'desc' => '服'),
            ),
        );
    }

    /**
     * new get-token
     * @desc 多条件查询接口
     * @return array data 被查数据
     * @exception 400 非法请求，参数传递错误
     */
    public function newRest()
    {
        header('Access-Control-Allow-Origin:*');

        $imei = $this->imei;
        $note = $this->note;
        $phone_name = $this->phone_name;
        if (!$phone_name) {
            $phone_name = '未设置';
        }
        //读出过来的ip
        $ip = $_SERVER["REMOTE_ADDR"];
        //查询一下是否有手机信息
        $imeiinfo = Checkimei($imei, $phone_name, $note ,$ip);

        $userinfo = \PhalApi\DI()->notorm->rok_user->where("username",$imeiinfo["user_id"])->fetchOne();
        if ( $userinfo['state'] == 0 ){
            return array(
                'msg'  => '休息',
                'show' => '临时禁用'
            );
        }

        //读出该ip下的所有手机
        //$ip_count = \PhalApi\DI()->notorm->rok_imei->where("ip",$ip)->fetchAll();

        //修正正在运行的帐号的显示问题
        \PhalApi\DI()->notorm
            ->rok_account
            ->where(array('imei_id' => $imeiinfo['id'], 'state'=> '运行中',))
            ->update(array('todo'=> 'no', 'state'=> '', 'show_state' => '',));

        //读出今天的单双问题
        $dayNumber = date("d", time());
        $dayNumber = $dayNumber % 2;
        //设置好单双
        $daylist = array('双', '单');
        $getWhere = array($daylist[$dayNumber], '全');

        //读出是否需要冷却
        if ($imeiinfo['switch']) {
            $imeiinfo['rest_time'] = 0;
        } else {
            $imeiinfo['time_line'] = json_decode( $imeiinfo['time_line'] ,true );

            $dataTime = date("H:i:s", time());

            //去掉随机，改为设置的大小
            //            $imeiinfo['rest_time'] = $imeiinfo['rest_time'] + mt_rand(2, 8);
            if ($dataTime > $imeiinfo['time_line'][0] && $dataTime <  $imeiinfo['time_line'][1]  ) {
                return array(
                    'msg'  => '休息',
                    'show' => '设置休息'
                );
            }
        }

        //整理好条件读出来可以跑的帐号
        $where = array(
            'imei_id'   => $imeiinfo['id'],
            'user_id'   => $imeiinfo['user_id'],
            'switch'    => 0,
            'time < ?'  => date("Y-m-d H:i:s", time() - 60 * $imeiinfo['rest_time']),
            'rest_type' => $getWhere
        );

        //按时间排序读出
        $tokeninfo = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->order('time ASC')
            ->fetchOne();

        //对读出的信息进行 归类统计
        if ($tokeninfo) {

            //如果读出了帐号,则下一个号的时间随机一下
//            if ( $imeiinfo ){
//                \PhalApi\DI()->notorm->rok_imei->where("id",$imeiinfo['id'])
//                    ->update(array(
//                    "rest_time" => mt_rand(30,80)));
//            }
            //查询ip
            $ipinfo = \PhalApi\DI()->notorm->rok_ip
                ->where(array(
                    'date' => date("Y-m-d", time()),
                    'ip'   => $ip,
                ))
                ->fetchOne();
            if ($ipinfo) {
                \PhalApi\DI()->notorm->rok_ip
                    ->where("id", $ipinfo['id'])
                    ->update(array(
                        "count" => $ipinfo['count'] + 1
                    ));
            } else {
                $get_ip_info_url = "http://api.okayapi.com/?s=Ext.IP.GetInfo&return_data=0&ip=" . $ip . "&app_key=90BB9337D7B1ACC0CA642C5726D227CB";
                // 小白接口的读ip接口 url
                $curl = new \PhalApi\CUrl();
                // 第二个参数，表示超时时间，单位为毫秒
                $rs = $curl->get($get_ip_info_url, 3000);
                if ($rs) {
                    $rs = json_decode($rs, true);
                    $address = $rs['data']['data']['country'] . $rs['data']['data']['region'] . $rs['data']['data']['city'] . $rs['data']['data']['isp'];
                }

                \PhalApi\DI()->notorm->rok_ip
                    ->where("id", $ipinfo['id'])
                    ->insert(array(
                        'ip'      => $ip,
                        "date"    => date("Y-m-d", time()),
                        "address" => $address,
                        "count"   => 1,
                        "time"    => date("Y-m-d H:i:s", time()),
                        "addtime" => date("Y-m-d H:i:s", time()),
                    ));
            }

            //如果发现已经过期则发一个推送到手机上来
            if ($tokeninfo['due_time'] < date("Y-m-d H:i:s", time())) {
                $curl = new \PhalApi\CUrl();
                $iphonexUrl = "https://api.day.app/4ZUHoSqcS5STLaduTTDarZ/" . $tokeninfo['note'] . "/" . $imeiinfo['imei'] . "-" . $tokeninfo['due_time'] . "-已经到期,请处理";
//                $rs = $curl->get($iphonexUrl, 500);
            }

            $yz = \App\rok_token_record($tokeninfo['id'], $tokeninfo['user_id']);
            if ($yz) {
                //  有帐号更新一下状态
                $web_ui = json_decode($tokeninfo['web_ui'], true);
                $web_ui['支线功能']['远征'] = false;
                $web_ui['支线功能']['英雄加点'] = false;
                $tokeninfo['web_ui'] = json_encode($web_ui);
            }

            $update = \PhalApi\DI()->notorm
                ->rok_account
                ->where('id', $tokeninfo['id'])
                ->update(array(
                        'todo'  => 'todo',
                        'state' => '运行中',
                        'time'  => date("Y-m-d H:i:s", time())
                    )
                );
            $tokeninfo['is_awz'] = $imeiinfo['is_awz'];
            $tokeninfo['is_vpn'] = $imeiinfo['is_vpn'];

            $showText = "";
            return $tokeninfo;
        }

        $where = array(
            'imei_id' => $imeiinfo['id'],
            'user_id' => $imeiinfo['user_id'],
            'switch'  => 0,
        );
        $tokeninfo = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->order('time ASC')
            ->fetchOne();

        if ($tokeninfo) {
            $gametime = strtotime($tokeninfo['time']);
            $nowtime = time();
            return array(
                'msg'  => '休息',
                'show' => $tokeninfo['note'] . intval($imeiinfo['rest_time'] * 60 - ($nowtime - $gametime)),
            );
        }

        return array(
            'msg'  => '休息',
            'show' => '暂无帐号'
        );

    }



    /**
     * rok-token
     * @desc 多条件查询接口
     * @return array data 被查数据
     * @exception 400 非法请求，参数传递错误
     */
    public function Rest()
    {
        header('Access-Control-Allow-Origin:*');

        $imei = $this->imei;
        $note = $this->note;
        $phone_name = $this->phone_name;
        if (!$phone_name) {
            $phone_name = '未设置';
        }
        $ip = $_SERVER["REMOTE_ADDR"];
        $imeiinfo = Checkimei($imei, $phone_name, $note,$ip);
        \PhalApi\DI()->notorm
            ->rok_account
            ->where(array(
                'imei_id' => $imeiinfo['id'],
                'state'   => '运行中',
            ))
            ->update(array(
                    'todo'       => 'no',
                    'state'      => '',
                    'show_state' => '',
                )
            );


        $dayNumber = date("d", time());
        $dayNumber = $dayNumber % 2;

        $daylist = array('双', '单');
        $getWhere = array($daylist[$dayNumber], '全');


        if ($imeiinfo['switch']) {
            $imeiinfo['rest_time'] = 0;
        } else {
            $dataTime = date("H:i:s", time());
//            $imeiinfo['rest_time'] = $imeiinfo['rest_time'] + mt_rand(2, 8);
            if ($dataTime > "01:00:00" && $dataTime < "06:00:00") {
                return array(
                    'msg'  => '休息',
                    'show' => '1-6点,系统休息'
                );
            }
        }

        $where = array(
            'imei_id'   => $imeiinfo['id'],
            'user_id'   => $imeiinfo['user_id'],
            'switch'    => 0,
            'time < ?'  => date("Y-m-d H:i:s", time() - 60 * $imeiinfo['rest_time']),
            'rest_type' => $getWhere
        );

        $tokeninfo = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->order('time ASC')
            ->fetchOne();

        if ($tokeninfo) {
            $ip = $_SERVER["REMOTE_ADDR"];
            $ipinfo = \PhalApi\DI()->notorm->rok_ip
                ->where(array(
                    'date' => date("Y-m-d", time()),
                    'ip'   => $ip,
                ))
                ->fetchOne();
            if ($ipinfo) {
                \PhalApi\DI()->notorm->rok_ip
                    ->where("id", $ipinfo['id'])
                    ->update(array(
                        "count" => $ipinfo['count'] + 1
                    ));
            } else {
                $get_ip_info_url = "http://api.okayapi.com/?s=Ext.IP.GetInfo&return_data=0&ip=" . $ip . "&app_key=90BB9337D7B1ACC0CA642C5726D227CB";
                // 先实例
                $curl = new \PhalApi\CUrl();
                // 第二个参数，表示超时时间，单位为毫秒
                $rs = $curl->get($get_ip_info_url, 3000);
                if ($rs) {
                    $rs = json_decode($rs, true);
                    $address = $rs['data']['data']['country'] . $rs['data']['data']['region'] . $rs['data']['data']['city'] . $rs['data']['data']['isp'];
                }

                \PhalApi\DI()->notorm->rok_ip
                    ->where("id", $ipinfo['id'])
                    ->insert(array(
                        'ip'      => $ip,
                        "date"    => date("Y-m-d", time()),
                        "address" => $address,
                        "count"   => 1,
                        "time"    => date("Y-m-d H:i:s", time()),
                        "addtime" => date("Y-m-d H:i:s", time()),
                    ));
            }

            //如果发现已经过期则发一个推送到手机上来
            if ($tokeninfo['due_time'] < date("Y-m-d H:i:s", time())) {
                $curl = new \PhalApi\CUrl();
                $iphonexUrl = "https://api.day.app/4ZUHoSqcS5STLaduTTDarZ/" . $tokeninfo['note'] . "/" . $imeiinfo['imei'] . "-" . $tokeninfo['due_time'] . "-已经到期,请处理";
//                $rs = $curl->get($iphonexUrl, 500);
            }

            $yz = \App\rok_token_record($tokeninfo['id'], $tokeninfo['user_id']);
            if ($yz) {
                //  有帐号更新一下状态
                $web_ui = json_decode($tokeninfo['web_ui'], true);
                $web_ui['支线功能']['远征'] = false;
                $web_ui['支线功能']['英雄加点'] = false;
                $tokeninfo['web_ui'] = json_encode($web_ui);
            }

            $update = \PhalApi\DI()->notorm
                ->rok_account
                ->where('id', $tokeninfo['id'])
                ->update(array(
                        'todo'  => 'todo',
                        'state' => '运行中',
                        'time'  => date("Y-m-d H:i:s", time())
                    )
                );
            $tokeninfo['is_awz'] = $imeiinfo['is_awz'];
            return $tokeninfo;
        }

        $where = array(
            'imei_id' => $imeiinfo['id'],
            'user_id' => $imeiinfo['user_id'],
            'switch'  => 0,
        );
        $tokeninfo = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->order('time ASC')
            ->fetchOne();

        if ($tokeninfo) {
            $gametime = strtotime($tokeninfo['time']);
            $nowtime = time();
            return array(
                'msg'  => '休息',
                'show' => $tokeninfo['note'] . intval($imeiinfo['rest_time'] * 60 - ($nowtime - $gametime)),
            );
        }

        return array(
            'msg'  => '休息',
            'show' => '暂无帐号'
        );


    }


    /**
     * rok-分区接口
     * @desc 多条件查询接口
     * @return array data 被查数据
     * @exception 400 非法请求，参数传递错误
     */
    public function Qu()
    {
        header('Access-Control-Allow-Origin:*');
        $qus = $this->qus;

        \PhalApi\DI()->notorm
            ->rok_account
            ->where(array(
                'imei_id' => 88,
                'state'   => '运行中',
            ))
            ->update(array(
                    'todo'  => 'no',
                    'state' => '',
                )
            );

        $where = array(
            'imei_id' => 88,
            'switch'  => 0,
            'qus'     => $qus
        );

        $token = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->fetchOne();

        if ($token) {

            \PhalApi\DI()->notorm
                ->rok_account
                ->where('id', $token['id'])
                ->update(array(
                        'todo'  => 'todo',
                        'state' => '运行中',
                        'time'  => date("Y-m-d H:i:s", time())
                    )
                );
            return $token;
        }

        $where = array(
            'qus'        => $qus,
            'switch'     => 0,
            'state != ?' => '运行中'
        );

        $token = \PhalApi\DI()->notorm->rok_account
            ->where($where)
            ->fetchOne();

        if ($token) {
            \PhalApi\DI()->notorm
                ->rok_account
                ->where('id', $token['id'])
                ->update(array(
                        'todo'    => 'todo',
                        'state'   => '运行中',
                        'imei_id' => 88,
                        'time'    => date("Y-m-d H:i:s", time())
                    )
                );
            return $token;
        }


    }
}
